package com.demo.richText.framework;

import com.demo.richText.Enum.MessageEnum;
import com.demo.richText.exception.RichException;
import com.demo.richText.util.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;



/**
 * @author: 小乌龟
 * @Date: 2022/1/11
 * @Describe:
 */
@Slf4j
public abstract class CommonController {

    /**
     *
     * @param br
     * @param <M>
     * @return
     */
    public <M> ResultResponse<M> process(BindingResult br){
        if (br.hasErrors()){
            return errorResult(br);
        }else {
            return successResult();
        }
    }

    public <M> ResultResponse<M> process(Supplier<M> sp){
        try {
            M val = sp.get();
            if (ObjectUtils.isEmpty(val)){
                return ResultResponse.fail(MessageEnum.MESSAGE_NOT_FOUND,null);
            }
            return ResultResponse.ok(val);
        }catch (RichException e) {
            return ResultResponse.customException(e);
        }
    }

    public <M> ResultResponse<M> process(Supplier<M> sp, BindingResult br){
        if (br.hasErrors()){
            return errorResult(br);
        }else {
           return process(sp);
        }
    }

    private <M> ResultResponse<M> errorResult(BindingResult br) {
        List<String> errs = br.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        return (ResultResponse<M>) ResultResponse.fail(MessageEnum.PARAMETER_ERROR.getCode(),errs.get(0),errs);
    }


    private <M> ResultResponse<M>  successResult() {
        ResultResponse<M> resultResponse = new ResultResponse<>();
        resultResponse.setCode(MessageEnum.OK.getCode());
        resultResponse.setMsg(MessageEnum.OK.getMessage());
        resultResponse.setData(null);
        return resultResponse;
    }

















}
